<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @submit.native.prevent="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="资料名称" size="small">
            <el-input v-model="searchForm.dataName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>

      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        label="操作"
        fixed="right"
        width="80">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.borrowId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
        <el-form-item prop="dataName" label="外借资料" size="small">
          <el-input type="textarea" v-model="teamRow.dataName"></el-input>
        </el-form-item>
        <el-form-item prop="startTimeStr" label="外借时间" size="small">
          <el-date-picker
            v-model="teamRow.startTimeStr"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
            @change="dateChangebirthday"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="endTimeStr" label="预计归还时间" size="small">
          <el-date-picker
            v-model="teamRow.endTimeStr"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="borrowPerson" label="外借人" size="small">
          <el-input type="text" v-model="teamRow.borrowPerson"></el-input>
        </el-form-item>
        <el-form-item prop="contact" label="联系方式" size="small">
          <el-input type="text" v-model="teamRow.contact"></el-input>
        </el-form-item>
        <el-form-item prop="outPerson" label="借出人" size="small">
          <el-input type="text" v-model="teamRow.outPerson"></el-input>
        </el-form-item>
        <el-form-item prop="isReturn" label="是否归还" size="small">
          <el-switch
            v-model="teamRow.isReturn"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value=1
            :inactive-value=0
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="备注说明" size="small">
          <el-input type="textarea" v-model="teamRow.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    deleteInfoborrowlog,
    getProjectborrowList,
    insertInfoborrowlog,
    selectInfoborrowlog,
    selectInfoTitle,
    updateInfoborrowlog
  } from '@/api/infoborrowlog'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'
  import { isvalidPhone } from '@/utils/validate'

  const dateBorrow = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const preDateReturn = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const isReturn = function(row, column) {
    return row.isReturn ? '是' : '否'
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (!isvalidPhone(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        colConfigs: [
          { prop: 'dataName', label: '资料名称', minWidth: '100%', fixed: true },
          { prop: 'dateBorrow', label: '外借时间', width: '100', component: dateBorrow },
          { prop: 'preDateReturn', label: '预计归还时间', width: '120', component: preDateReturn },
          { prop: 'borrowPerson', label: '外借人', width: '80' },
          { prop: 'contact', label: '联系方式', width: '80' },
          { prop: 'outPerson', label: '借出人', width: '80' },
          { prop: 'isReturn', label: '是否归还', width: '80', formatter: isReturn },
          { prop: 'remark', label: '备注说明', width: '160' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '新增外借资料',
        dialogType: 0,
        teamRow: {
          dataName: '',
          dateBorrow: '',
          preDateReturn: '',
          borrowPerson: '',
          contact: '',
          outPerson: '',
          isReturn: 0,
          remark: ''
        },
        teamRowClear: {
          dataName: '',
          dateBorrow: '',
          preDateReturn: '',
          borrowPerson: '',
          contact: '',
          outPerson: '',
          isReturn: 0,
          remark: ''
        },
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {
          dataName: [
            { required: true, message: '请选择资料', trigger: 'change' }
          ],
          startTimeStr: [
            { required: true, message: '请选择外借时间', trigger: 'change' }
          ],
          endTimeStr: [
            { required: true, message: '请选择预计归还时间', trigger: 'change' }
          ],
          borrowPerson: [
            { required: true, message: '请填写外借人', trigger: 'change' }
          ],
          isReturn: [
            { required: true, message: '请选择是否归还', trigger: 'change' }
          ],
          contact: [
            { required: false, trigger: 'change', validator: validPhone }
          ]
        },
        visible: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        console.log(this.searchFormList)
        getProjectborrowList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.dialogTitle = '新增外借资料'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.teamRow.isTender = 1
        this.dialogType = 1
      },
      editTeam(borrowId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改外借资料'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          borrowId: borrowId
        }
        selectInfoborrowlog(params).then(response => {
          this.teamRow = response.responseBody
          this.$set(this.teamRow, 'startTimeStr', formatDate(new Date(this.teamRow.dateBorrow), 'yyyy-MM-dd'))
          this.$set(this.teamRow, 'endTimeStr', formatDate(new Date(this.teamRow.preDateReturn), 'yyyy-MM-dd'))
          this.teamRow.infoTitle = this.teamRow.dataName
        })
      },
      submitForm(formName) {
        const params = {
          dataName: this.teamRow.dataName,
          outPerson: this.teamRow.outPerson ? this.teamRow.outPerson : '',
          infoId: this.teamRow.infoId,
          startTimeStr: this.teamRow.startTimeStr,
          endTimeStr: this.teamRow.endTimeStr,
          borrowPerson: this.teamRow.borrowPerson,
          contact: this.teamRow.contact ? this.teamRow.contact : '',
          isReturn: this.teamRow.isReturn,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        if (!this.dialogType) {
          params.borrowId = this.teamRow.borrowId
          params.infoTitle = this.teamRow.infoTitle
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              insertInfoborrowlog(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateInfoborrowlog(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          borrowId: scope.row.borrowId,
          dataName: scope.row.dataName,
          isDel: 1
        }
        deleteInfoborrowlog(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      dateChangebirthday(val) {
        console.log(val)
        this.teamRow.startTimeStr = val
        console.log(this.teamRow)
      },
      querySearchInfoTitle(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.infoId
        if (queryString) {
          const params = {
            infoTitle: queryString
          }
          selectInfoTitle(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.infoTitle
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectInfoTitle(item) {
        this.teamRow.infoId = item.infoId
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
